package com.ithuang.quartz.task;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;


/**
 * 咸鱼
 */
// @Component("task3")
public class Task3 {
    @Value("${spring.mail.username}")
    private String username;
    
    @Autowired
    private JavaMailSender mailSender;
    static{
        System.setProperty("mail.mime.splitlongparameters","false");
        System.setProperty("mail.mime.charset","UTF-8");
    }
    @PostConstruct
    public void handle() throws InterruptedException, MessagingException, IOException {

        // String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        // System.out.println(jarPath);
// String jarPath = null;
//         try {
//             jarPath = new File(Application.class.getProtectionDomain()
//                     .getCodeSource().getLocation().toURI()).getPath();
//                     System.out.println(jarPath);
//         } catch (URISyntaxException e) {
//             e.printStackTrace();
//         }
        String currentDirectory = System.getProperty("user.dir");
        // System.out.println("当前程序所在路径：" + currentDirectory);
        String dizhiPath = currentDirectory+File.separator+"地址.txt";

        File dizhiFile = new File(dizhiPath);
        String mails = FileCopyUtils.copyToString(new FileReader(dizhiFile));
        String[] ar = mails.split("\r\n");
        
        
        String neirongPath = currentDirectory+File.separator+"neirong.txt";
        // File neirongFile = new File(neirongPath);
        FileInputStream fis = new FileInputStream(neirongPath);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");

        String neirong = FileCopyUtils.copyToString(isr);

        // File currentDirectory2 = new File(".");
        // String absolutePath = currentDirectory2.getAbsolutePath();
        // System.out.println("当前程序所在路径2：" + absolutePath);


        MimeMessage message = mailSender.createMimeMessage();
        // 文本内容
        MimeBodyPart txt = new MimeBodyPart();
        String c = buildContent("接收人007", "wu标题0", neirong);
        txt.setContent(c, "text/html;charset=UTF-8");
        txt.addHeader("chartset", "text/html;charset=UTF-8");
        // bodyPartText.setText(c, "UTF-8");
        // 图片内容
        MimeBodyPart img = new MimeBodyPart();
        
        String zhengwenjpg = currentDirectory+File.separator+"正文.jpg";
        Path p = Paths.get(zhengwenjpg);
        byte[] bs = Files.readAllBytes(p);
        ByteArrayDataSource sour = new ByteArrayDataSource(bs, "application/octet-stream");
        img.setDataHandler(new DataHandler(sour));
        img.setContentID("cbkj");
        // 附件内容
        MimeBodyPart tach = new MimeBodyPart();
        String fujianjpg = currentDirectory+File.separator+"附件.jpg";
        DataHandler dh = new DataHandler(new FileDataSource(fujianjpg));
        tach.setDataHandler(dh);
        tach.setFileName(dh.getName());
        // 关系:正文和图片
        MimeMultipart muti1 = new MimeMultipart();
        muti1.addBodyPart(txt);
        muti1.addBodyPart(img);
        muti1.setSubType("related");
        // 关系:正文和附件
        MimeMultipart muti2 = new MimeMultipart();
        muti2.addBodyPart(tach);
        // 全文内容
        MimeBodyPart allbody = new MimeBodyPart();
        allbody.setContent(muti1);
        muti2.addBodyPart(allbody);
        muti2.setSubType("mixed");
        // 封装 MimeMessage 对象
        message.setContent(muti2);
        message.setSubject("测试发送邮件");
        message.saveChanges();
        // // 本地查看文件格式
        // message.writeTo(new FileOutputStream("F:\\MixedMail.eml"));
        // message.addRecipient(javax.mail.Message.RecipientType.TO, new
        // InternetAddress("mingyang002@163.com") );
        InternetAddress[] to_mail= new InternetAddress[ar.length];
        for (int i = 0; i < ar.length; i++) {
            to_mail[i] = new InternetAddress(ar[i]);
        }

        message.addRecipients(javax.mail.Message.RecipientType.TO, to_mail);
        message.addRecipients(javax.mail.Message.RecipientType.TO, "jonsnow666@yeah.net");
        System.out.println(username);
        message.setFrom(new InternetAddress(username));

        
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        
        // 给定时间（格式：yyyy-MM-dd HH:mm:ss）
        String givenTimeStr = "2028-5-11 21:03:00";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date givenTime = null;
        try {
            givenTime = dateFormat.parse(givenTimeStr);
        } catch (ParseException e) {
            System.err.println("时间格式错误，请使用 yyyy-MM-dd HH:mm:ss 格式");
            return;
        }

        if(System.currentTimeMillis()<givenTime.getTime()){
            mailSender.send(message);
        }
        

    }

    @Autowired
    private ResourceLoader resourceLoader;
    /**
     * 封装模板
     * 
     * @param name    接收人姓名
     * @param title   标题
     * @param content 内容
     * @return
     * @throws IOException
     */
    public String buildContent(String name, String title, String content) throws IOException {
        // Date date = new Date();
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 加载邮件html模板
        // File fileName = new File("D:\\mailtemplete.html"); // windows绝对路径
        // File fileName = new File("/opt/template/mailtemplete.html"); // linux绝对路径
        // File fileName = new File("src/main/resources/mailtemplete.html"); // 相对路径
        // File file = new File("temp.html");
        // InputStream stream = this.getClass().getResourceAsStream("//template.html");

        Resource resource = resourceLoader.getResource("classpath:template.html");
        InputStream  in = resource.getInputStream();
        
        // FileUtils.copyInputStreamToFile(stream, file);
        // Files.readAllLines(resource., null)

        BufferedReader fileReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {

        } finally {
            fileReader.close();
        }
        // 替换参数
        String htmlText = buffer.toString();
        htmlText = htmlText.replace("{name}", name);
        // htmlText = htmlText.replace("{date}",sdf.format(date));
        // htmlText = htmlText.replace("{title}",title);
        htmlText = htmlText.replace("{content}", content);
        /*
         * 也可以用以下替换参数，但是我使用时报错了，若用以下替换参数的话，邮件模板（html）里面的“{title}”，“{content}”等替换成“{0}”，“
         * {1}”等
         * List<String> list = new ArrayList<>();
         * list.add(name);
         * list.add(sdf.format(date));
         * list.add(title);
         * list.add(content);
         * String htmlText = MessageFormat.format(buffer.toString(), list);
         */
        return htmlText;
    }
  
    /**
     * 封装模板
     * 
     * @param name    接收人姓名
     * @param title   标题
     * @param content 内容
     * @return
     * @throws IOException
     */
    public String buildContent2(String name, String title, String content) throws IOException {
        // Date date = new Date();
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 加载邮件html模板
        // File fileName = new File("D:\\mailtemplete.html"); // windows绝对路径
        // File fileName = new File("/opt/template/mailtemplete.html"); // linux绝对路径
        // File fileName = new File("src/main/resources/mailtemplete.html"); // 相对路径
        File file = new File("mailtemplete.html");
        InputStream stream = this.getClass().getResourceAsStream("//mailtemplete2.html");
        FileUtils.copyInputStreamToFile(stream, file);
        BufferedReader fileReader = new BufferedReader(new FileReader(file));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {

        } finally {
            fileReader.close();
        }
        // 替换参数
        String htmlText = buffer.toString();
        htmlText = htmlText.replace("{name}", name);
        // htmlText = htmlText.replace("{date}",sdf.format(date));
        // htmlText = htmlText.replace("{title}",title);
        htmlText = htmlText.replace("{content}", content);
        /*
         * 也可以用以下替换参数，但是我使用时报错了，若用以下替换参数的话，邮件模板（html）里面的“{title}”，“{content}”等替换成“{0}”，“
         * {1}”等
         * List<String> list = new ArrayList<>();
         * list.add(name);
         * list.add(sdf.format(date));
         * list.add(title);
         * list.add(content);
         * String htmlText = MessageFormat.format(buffer.toString(), list);
         */
        return htmlText;
    }
  
}
